package com.itheima.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.itheima.excel.StudentModel;
import com.itheima.excel.StudentReaderListener;
import com.itheima.pojo.PageResult;
import com.itheima.pojo.Result;
import com.itheima.pojo.Student;
import com.itheima.pojo.StudentQueryParam;
import com.itheima.service.StudentService;
import jakarta.validation.Valid;
import jakarta.validation.constraints.Positive;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

/**
 * @version 1.0
 * @description 说明
 * @package com.itheima.controller
 */
@RestController
@Slf4j
@AllArgsConstructor
@RequestMapping("/students")
@Valid
public class StudentController {

    private StudentService studentService;

    @GetMapping
    public Result pageQuery(StudentQueryParam studentQueryParam){
        PageResult<Student> pageResult = studentService.pageQuery(studentQueryParam);
        return Result.success(pageResult);
    }

    @PostMapping
    public Result add(@Valid @RequestBody Student student){
        studentService.add(student);
        return Result.success();
    }

    @GetMapping("/{id}")
    public Result getById(@PathVariable Integer id){
        return Result.success(studentService.getById(id));
    }

    @PutMapping
    public Result update(@RequestBody Student student){
        studentService.updateById(student);
        return Result.success();
    }

    @DeleteMapping("/{id}")
    public Result deleteById(@PathVariable Integer id){
        studentService.deleteById(id);
        return Result.success();
    }

    @PutMapping("/violation/{id}/{score}")
    public Result violation(@PathVariable Integer id, @Positive(message = "分数不能为空或负数") @PathVariable Integer score){
        studentService.violation(id,score);
        return Result.success();
    }

    /**
     * 批量导入
     */
    @PostMapping("/import/{clazzId}")
    public Result importExcel(@PathVariable Integer clazzId, MultipartFile file) throws IOException {
        //EasyExcel封装的方法
        EasyExcel.read(file.getInputStream(), //文件的输入流
                        StudentModel.class, // 解析每行数据，映射成实体类
                        new StudentReaderListener(studentService,clazzId)// 读取数据的处理器 事件监听
                )
                .sheet().doRead();
        return Result.success();
    }

}
